package com.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.InetAddress;
import java.net.UnknownHostException;

@RestController
public class TestController {
    @Value("${spring.application.name}")
    private String appName;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @RequestMapping("/test")
    public String test(){
        String app2 = appName;

        //微服务调用方式一
        ServiceInstance serviceInstance = loadBalancerClient.choose(app2);
        String path = String.format("http://%s:%s/echo/%s",serviceInstance.getHost(),serviceInstance.getPort(),appName);
        System.out.println("request path:" +path);
        //微服务调用方式二
        String str = "我是:"+appName+"。调用服务:"+app2+"获得:【"+this.clientApp(app2)+"】。";
        return str;
    }

    @RequestMapping("/app")
    public String app() throws UnknownHostException {
        InetAddress addr = InetAddress.getLocalHost();
        return "我是,"+appName+",ip是,"+addr.getHostAddress();
    }

    protected String clientApp(String app){
        String path = String.format("http://%s/app", app);
        return restTemplate.getForObject(path, String.class);
    }
}
